package com.vitaf.cash.app.ui.activity

import android.annotation.SuppressLint
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.lifecycleScope
import com.vitaf.cash.app.R
import com.vitaf.cash.app.base.app.VitafActStackManager
import com.vitaf.cash.app.common.VitafComActV2
import com.vitaf.cash.app.configs.GombeCreditApiPath
import com.vitaf.cash.app.configs.GombeCreditApiUrl
import com.vitaf.cash.app.configs.GombeCreditApiUrl.addCommonParams
import com.vitaf.cash.app.databinding.DataBindingHelper
import com.vitaf.cash.app.databinding.VitafActMainBinding
import com.vitaf.cash.app.event.VitafEventData
import com.vitaf.cash.app.request.IHttpCallback
import com.vitaf.cash.app.ui.dialog.VitafUpdateDlog
import com.vitaf.cash.app.ui.fragment.TabHomeFragment
import com.vitaf.cash.app.ui.fragment.TabUserFragment
import com.vitaf.cash.app.utils.VitafDateUtil
import com.vitaf.cash.app.utils.VitafTitleBarUtil
import com.vitaf.cash.app.utils.helper.TestDataLibInvoke
import com.vitaf.cash.app.utils.helper.VitafConfigsHp
import com.vitaf.cash.app.utils.helper.VitafProcessHp
import com.vitaf.cash.app.utils.helper.VitafUpdateHp
import com.vitaf.cash.app.utils.log.VitafLog
import com.vitaf.cash.app.utils.shared.VitafSharedHp
import com.vitaf.cash.app.utils.shared.VitafSharedKey
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

/**
 * VitafCash
 * @Author wwdeng
 * @CreateTime: 2024/11/28 14:39
 * @Annotation：主页
 */
class VitafMainAct: VitafComActV2(){
    private var _binding: VitafActMainBinding? = null
    //首页
    private var homeFragment: TabHomeFragment? = null
    //个人中心
    private var mainMenuFragment: TabUserFragment? = null

    private var viewModel = DataBindingHelper.createModel()

    private var updateHelper: VitafUpdateHp? = null
    private val updateLauncher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            //更新成功

        } else {

        }
    }

    override val pageName: String = "Main_Page"

    override val enablePageTrack: Boolean = false

    override fun createVitafContentView(): View? {
        _binding = DataBindingUtil.setContentView(this, R.layout.vitaf_act_main)
        _binding?.model = viewModel
        _binding?.activity = this
        _binding?.lifecycleOwner = this
        return null
    }

    override fun initializeVitafViews() {
        setBackExit(true)
        VitafTitleBarUtil.setStatusBarLightMode(this@VitafMainAct, true)
        //移除流程接口数据
        VitafSharedHp.deleteGombeCreditSharedData(VitafSharedKey.GOMBECREDIT_PROCESS)
    }

    override fun setupVitafEventListeners() {
    }

    override fun loadVitafData() {
        showVitafLoading()
        lifecycleScope.launch {
            //延迟加载
            delay(500)
            loadGombeCreditProcessAction()
        }

        onClickMainLoan()

        //是否有新版本
        val isUpdate = VitafConfigsHp.isGombeCreditUpdate()
        if (isUpdate){
            showGombeCreditUpdateDialog()
        }
    }

    /**
     * 点击LOAN
     */
    fun onClickMainLoan(){
        viewModel.set("isSelectLoan",true)
        viewModel.set("isSelectMe",false)
        showGombeCreditMainHomePage()
    }

    /**
     * 点击ME
     */
    fun onClickMainMe(){
        viewModel.set("isSelectLoan",false)
        viewModel.set("isSelectMe",true)
        showGombeCreditMainMenuPage()
    }

    /**
     * 隐藏所有的页面
     */
    @SuppressLint("CommitTransaction")
    private fun hideGombeCreditAllFragment(): FragmentTransaction {
        val fragmentManager = supportFragmentManager
        val transaction = fragmentManager.beginTransaction()
        fragmentManager.fragments.forEach { fragment ->
            transaction.hide(fragment)
        }
        transaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
        return transaction
    }

    /**
     * 显示首页
     */
    private fun showGombeCreditMainHomePage(){
        if (homeFragment == null) {
            homeFragment = TabHomeFragment()
        }
        showFragmentPage(homeFragment)
    }

    /**
     * 显示个人中心
     */
    private fun showGombeCreditMainMenuPage(){
        if (mainMenuFragment == null) {
            mainMenuFragment = TabUserFragment()
        }
        showFragmentPage(mainMenuFragment)
    }

    /**
     * 显示Fragment页面
     */
    private fun showFragmentPage(fragment: Fragment?){
        val transaction = hideGombeCreditAllFragment()
        fragment?.let {
            if (fragment.isAdded) {
                transaction.show(fragment)
            } else {
                transaction.add(R.id.main_content_layout,fragment)
            }
        }
        transaction.commitAllowingStateLoss()
    }

    /**
     * 需要校验手机号
     */
    fun showGombeCreditMainMustCheckMobilePage() {
        //当前栈顶是 手机号校验页面 不重复跳转
        if (VitafActStackManager.isCurrentActivity(VitafVerifyMobileAct::class.java)){
            return
        }
        //是否是审核账号
        val isAdmin = VitafSharedHp.takeGombeCreditSharedBoolean(VitafSharedKey.GOMBECREDIT_IS_CONFIG_ACCOUNT)
        if(isAdmin) {//审核账号，直接不走校验
            return
        }
        VitafVerifyMobileAct.start(this)
    }

    /**
     * 版本更新Dialog
     */
    private fun showGombeCreditUpdateDialog(){
        val lastShowTime = VitafSharedHp.takeGombeCreditSharedString(VitafSharedKey.GOMBECREDIT_UPDATE_VERSION_LAST_TIME)
        if (lastShowTime.isNotEmpty() && VitafDateUtil.isSameDay(lastShowTime.toLong(),System.currentTimeMillis())){
            return
        }
        VitafSharedHp.addGombeCreditSharedData(VitafSharedKey.GOMBECREDIT_UPDATE_VERSION_LAST_TIME,"${System.currentTimeMillis()}")
        val updateDialog = VitafUpdateDlog(this,"Launch page",object : VitafUpdateDlog.IDialogCallback{
            override fun onUpdateClick() {
                try {
                    if (updateHelper == null){
                        updateHelper = VitafUpdateHp(activity = this@VitafMainAct, forceUpdate = false, updateLauncher)
                    }
                    updateHelper?.checkAndStartUpdate { }
                } catch (e: Exception) {

                }
            }
        })
        updateDialog.show()
    }

    override fun onVitafPublishEvent(event: VitafEventData) {
        super.onVitafPublishEvent(event)
        VitafLog.e(">>>>>>>>>>main>>>>>>>>>>>sub event："+event.eventType)
        when(event.eventType){
            VitafEventData.TYPE.GOMBECREDIT_PROCESS_REFRESH -> {//刷新流程
                loadGombeCreditProcessAction()
            }
            VitafEventData.TYPE.GOMBECREDIT_PROCESS_REFRESHED -> {//流程刷新完成
                hideVitafLoading()
            }
            VitafEventData.TYPE.GOMBECREDIT_PRODUCT_REFRESH -> {//刷新产品列表
            }
            VitafEventData.TYPE.GOMBECREDIT_SHOW_HOME -> {//显示首页
                showGombeCreditMainHomePage()
            }
            VitafEventData.TYPE.GOMBECREDIT_SHOW_REPAY -> {//待还款
                showGombeCreditMainMenuPage()
            }
            VitafEventData.TYPE.GOMBECREDIT_SYC_ALL_DEVICE -> {//上报所有设备数据
                VitafLog.e(">>>>>>>>>>>>>>>>syc device all data ")
                //此通知只会在申贷完成之后发送
                TestDataLibInvoke.takeGombeCreditDeviceInfoTypesAction()
            }
            else -> {

            }
        }
    }

    /**
     * 获取总流程
     */
    private fun loadGombeCreditProcessAction(){
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_PROCESS_PATH)
        }
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                //保存用户流程状态
                if (obj != null) {
                    // TODO: 测试添加 Step 类型
//                    val allStepTitles = obj.optJSONArray("allStepTitles")
//                    allStepTitles.put("Account Info")
//                    allStepTitles.put("Ocr Info")
//                    allStepTitles.put("Face recognition")
//                    val allSteps = obj.optJSONArray("allSteps")
//                    allSteps.put("account_info")
//                    allSteps.put("ocr_info")
//                    allSteps.put("sefie_info")
//                    val steps = obj.optJSONArray("steps")
//                    steps.put("account_info")
//                    steps.put("sefie_info")
//                    steps.put("ocr_info")
//                    val index = Random.nextInt(3)
//                    when(index){
//                        0 -> {
//                            steps.put("ocr_info")
//                        }
//                        1 -> {
//                            steps.put("sefie_info")
//                        }
//                        else -> {
//                            steps.put("account_info")
//                        }
//                    }
                    //保存用户流程数据
                    VitafProcessHp.saveGombeCreditProcessData(obj)
                    //通知全局流程刷新完成
                    publishEventData(VitafEventData(VitafEventData.TYPE.GOMBECREDIT_PROCESS_REFRESHED))

                    // TODO: 2024-11-20 新增需求 此处需要判断是否需要校验手机号
                    if (VitafProcessHp.isGombeCreditCheckWhatsApp() || VitafProcessHp.isGombeCreditCheckSMS()){
                        showGombeCreditMainMustCheckMobilePage()
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
            }
        })
    }
}